
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <fcntl.h>
#include <unistd.h>

#include "thread.h"

#ifdef __cplusplus

Lib_Thread::Lib_Thread(void)
	: m_status(false)
	, m_create(false)
	, m_exit(false)
{
	pthread_mutex_init(&lock_work, NULL);
}

Lib_Thread::~Lib_Thread(void)
{
	threadExitSync();

	pthread_mutex_destroy(&lock_work);
}

bool Lib_Thread::threadActive(void)
{
	if(0 == pthread_create(&tid, NULL, Lib_Thread::threadMain, this))
	{
		setThreadCreate(true);
	}

	return getThreadCreate();
}

void *Lib_Thread::threadMain(void *arg)
{
	Lib_Thread *pObject = (Lib_Thread *)arg;

	pthread_detach(pthread_self());

	pObject->setThreadStatus(true);

	pObject->threadLoop();

	pObject->setThreadStatus(false);

	return (void*)0xDEADDEAD;
}

bool Lib_Thread::isThreadRunning(void)
{
	if(true == getThreadCreate() && true == getThreadStatus())
	{
		return true;
	}

	return false;
}

bool Lib_Thread::isThreadNeedExit(void)
{
	bool ret = false;

	pthread_mutex_lock(&lock_work);

	ret = m_exit;

	pthread_mutex_unlock(&lock_work);

	return ret;
}

void Lib_Thread::threadNeedExit(void)
{
	pthread_mutex_lock(&lock_work);

	m_exit = true;

	pthread_mutex_unlock(&lock_work);
}

void Lib_Thread::threadExitSync(void)
{
	printf("%s() enter\n", __func__);

	while(true == isThreadRunning())
	{
		printf("%s() let's thread exit\n", __func__);

		threadNeedExit();

		usleep(30000);
	}

	printf("%s() quit\n", __func__);
}

void Lib_Thread::setThreadStatus(bool status)
{
	pthread_mutex_lock(&lock_work);

	m_status = status;

	pthread_mutex_unlock(&lock_work);
}

bool Lib_Thread::getThreadStatus(void)
{
	bool ret = false;

	pthread_mutex_lock(&lock_work);

	ret = m_status;

	pthread_mutex_unlock(&lock_work);

	return ret;
}

void Lib_Thread::setThreadCreate(bool status)
{
	pthread_mutex_lock(&lock_work);

	m_create = status;

	pthread_mutex_unlock(&lock_work);
}

bool Lib_Thread::getThreadCreate(void)
{
	bool ret = false;

	pthread_mutex_lock(&lock_work);

	ret = m_create;

	pthread_mutex_unlock(&lock_work);

	return ret;
}

#endif
